//
//  AppDelegate.m
//  LHJY
//
//  Created by 伟大大 on 2018/4/29.
//  Copyright © 2018年 丁伟佳. All rights reserved.
//

#import "AppDelegate.h"
#import "SYViewController.h"
#import "NSBundle+Language.h"

//#import "YinDaoViewController.h"
//
//#import "CPViewController.h"
//#import "ZJViewController.h"
//#import "LessonsViewController.h"
//
//#import "NSURLSession+CorrectedResumeData.h"
#import "LoginViewController.h"
//#import "New_MYViewController.h"
//
//
//#import <ShareSDK/ShareSDK.h>
//#import <ShareSDKConnector/ShareSDKConnector.h>
//
////腾讯开放平台（对应QQ和QQ空间）SDK头文件
//#import <TencentOpenAPI/TencentOAuth.h>
//#import <TencentOpenAPI/QQApiInterface.h>
//
////微信SDK头文件
//#import "WXApi.h"
//
////#import "DataVerifier.h"
//
//#import <AlipaySDK/AlipaySDK.h>
////#import "AlixPayResult.h"
//
////新浪微博SDK头文件
//#import "WeiboSDK.h"
////新浪微博SDK需要在项目Build Settings中的Other Linker Flags添加"-ObjC"
//#import "JPUSHService.h"
//#import <UserNotifications/UserNotifications.h>
//
//#import <AdSupport/AdSupport.h>
//
//#import "MesgViewController.h"

#define IS_IOS10ORLATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10)

#define kAppViewTagBottomBtns        200

@interface AppDelegate ()
//<NSURLSessionDownloadDelegate,JPUSHRegisterDelegate,WXApiDelegate>


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.allowRotation = 0;
    
//    [WXApi registerApp:@"wx2a12e7a3f27d1d96"];
//    /**初始化ShareSDK应用
//
//     @param activePlatforms
//
//     使用的分享平台集合
//
//     @param importHandler (onImport)
//
//     导入回调处理，当某个平台的功能需要依赖原平台提供的SDK支持时，需要在此方法中对原平台SDK进行导入操作
//
//     @param configurationHandler (onConfiguration)
//
//     配置回调处理，在此方法中根据设置的platformType来填充应用配置信息
//
//     */
//    [ShareSDK registerApp:@"27145cab1aef5"
//
//          activePlatforms:@[
//
//                            @(SSDKPlatformTypeWechat),
//                            @(SSDKPlatformTypeQQ),
//                            ]
//                 onImport:^(SSDKPlatformType platformType)
//     {
//         switch (platformType)
//         {
//             case SSDKPlatformTypeWechat:
//                 [ShareSDKConnector connectWeChat:[WXApi class]];
//                 break;
//             case SSDKPlatformTypeQQ:
//                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
//                 break;
//             case SSDKPlatformTypeSinaWeibo:
//                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
//                 break;
//                 //             case SSDKPlatformTypeRenren:
//                 //                 [ShareSDKConnector connectRenren:[RennClient class]];
//                 //                 break;
//             default:
//                 break;
//         }
//     }
//          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
//     {
//
//         switch (platformType)
//         {
//
//             case SSDKPlatformTypeWechat:
//                 [appInfo SSDKSetupWeChatByAppId:@"wx2a12e7a3f27d1d96"
//                                       appSecret:@"c95d35c9eaf924c8d70cc9298da4239d"];
//                 break;
//             case SSDKPlatformTypeQQ:
//                 [appInfo SSDKSetupQQByAppId:@"1107469478"
//                                      appKey:@"k2pvXtVxgsW1m3Nr"
//                                    authType:SSDKAuthTypeBoth];
//                 break;
//
//             default:
//                 break;
//         }
//     }];
//
//    //JPUSH
//
//
//    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
//
//    // 3.0.0及以后版本注册可以这样写，也可以继续用旧的注册方式
//    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
//    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
//    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
//        //可以添加自定义categories
//        //    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
//        //      NSSet<UNNotificationCategory *> *categories;
//        //      entity.categories = categories;
//        //    }
//        //    else {
//        //      NSSet<UIUserNotificationCategory *> *categories;
//        //      entity.categories = categories;
//        //    }
//    }
//    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
//
//    // 3.0.0以前版本旧的注册方式
//    //  if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
//    //#ifdef NSFoundationVersionNumber_iOS_9_x_Max
//    //    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
//    //    entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
//    //    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
//    //#endif
//    //  } else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
//    //      //可以添加自定义categories
//    //      [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
//    //                                                        UIUserNotificationTypeSound |
//    //                                                        UIUserNotificationTypeAlert)
//    //                                            categories:nil];
//    //  } else {
//    //      //categories 必须为nil
//    //      [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
//    //                                                        UIRemoteNotificationTypeSound |
//    //                                                        UIRemoteNotificationTypeAlert)
//    //                                            categories:nil];
//    //  }
//
//    //如不需要使用IDFA，advertisingIdentifier 可为nil
//    [JPUSHService setupWithOption:launchOptions appKey:appKey
//                          channel:channel
//                 apsForProduction:isProduction
//            advertisingIdentifier:nil];
//
//    //2.1.9版本新增获取registration id block接口。
//    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
//        if(resCode == 0){
//            NSLog(@"registrationID获取成功：%@",registrationID);
//
//        }
//        else{
//            NSLog(@"registrationID获取失败，code：%d",resCode);
//        }
//    }];

    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"myLanguage"] && ![[[NSUserDefaults standardUserDefaults] objectForKey:@"myLanguage"] isEqualToString:@""]) {
        [NSBundle setLanguage:[[NSUserDefaults standardUserDefaults] objectForKey:@"myLanguage"]];
    }
    
    if([AppUtility screenHeight] > 480){
        
        theApp.autoSizeScaleX = [AppUtility screenWidth]/320;
        
        theApp.autoSizeScaleY = [AppUtility screenHeight]/569;
        
        UEXNSLog(@"theapp.screenHeight = %f",[AppUtility screenHeight]);
        
    }else{
        
        theApp.autoSizeScaleX = 1.0;
        
        theApp.autoSizeScaleY = 1.0;
        
    }
    
    [self.window makeKeyAndVisible];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    
    NSString *uid= @"";
    
    if (![AccountController isLogin])
    {
        uid =@"";
    }
    else
    {
        uid =[[AccountController getAccountInfo] objectForKey:@"id"];
    }
    
    [self toOther];
    
    
//    self.completionHandlerDictionary = @{}.mutableCopy;
//    self.backgroundSession = [self backgroundURLSession];
//
//    [self initLocalNotification];
//    // ios8后，需要添加这个注册，才能得到授权
//    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
//        UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
//        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
//                                                                                 categories:nil];
//        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
//        // 通知重复提示的单位，可以是天、周、月
//        self.localNotification.repeatInterval = 0;
//    } else {
//        // 通知重复提示的单位，可以是天、周、月
//        self.localNotification.repeatInterval = 0;
//    }
//
//    UILocalNotification *localNotification = [launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
//    if (localNotification) {
//        [self application:application didReceiveLocalNotification:localNotification];
//    }
    return YES;
}
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (_allowRotation == 1) {
        return UIInterfaceOrientationMaskAllButUpsideDown;//这个可以根据自己的需求设置旋转方向
        
    } else {
        return (UIInterfaceOrientationMaskPortrait);
        
    }
    
}
    
    
    
-(void)showBottomView{
    [_KlbottomView setHidden:NO];
    
}
-(void)hiddenBottomView{
    [_KlbottomView setHidden:YES];
}
-(void)toOther
{
    
    //    [self enterHomePage];
    //    return;
    
    
    //    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"AD_SHOW"];
    //    BOOL isFirst = [[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"];
    
//    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"firstLaunch"]) {
//
//
//        [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"firstLaunch"];
//
//        UEXNSLog(@"first 。。。。。");
//
////        [self initQiDongZhiShi];
//        [self islogin];
//
//    }else {
//
//        //进入主屏
//        [self islogin];
//
//        [self enterHomePage];
//        //        self.adLaunchView = [[AdLaunchView alloc] initWithFrame:self.window.bounds];
//        //        self.adLaunchView._delegate = self;
//        //        [self.window addSubview: self.adLaunchView];
//
//
//
//
//    }
    [self islogin];
    
//    [self enterHomePage];
    
}
- (void)islogin
{
    NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:KUDAppTDWNO];
    
    NSString *pass = [[NSUserDefaults standardUserDefaults] objectForKey:KUDAppTDWPass];
    
    
    if ([AppUtility isBlankString:name]&&[AppUtility isBlankString:pass]) {
        
        LoginViewController *rootC = [[LoginViewController alloc]init];
        UINavigationController *rootCNavController = [[UINavigationController alloc] initWithRootViewController:rootC];

        self.window.rootViewController = rootCNavController;
        [self.window makeKeyAndVisible];
    }
    else {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLaunch"];
        
        [self enterHomePage];
    }
}
- (void)logout
{
    LoginViewController *rootC = [[LoginViewController alloc]init];
    UINavigationController *rootCNavController = [[UINavigationController alloc] initWithRootViewController:rootC];

    self.window.rootViewController = rootCNavController;
    [self.window makeKeyAndVisible];
}

-(void)enterHomePage{
    
    
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
    
    
    //访问服务器
    //    [NSThread detachNewThreadSelector:@selector(startUpdate) toTarget:self withObject:nil];
    
    //    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone ];
    
    
    [self loginIn];
    
    
    
    
    //
    
//    [self initBottomView];
    
}
- (void)loginIn
{
    NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:KUDAppTDWNO];
    
    NSString *pass = [[NSUserDefaults standardUserDefaults] objectForKey:KUDAppTDWPass];
    
    
    NSString *postStr = [NSString stringWithFormat:@"account=%@&password=%@&isApp=1",name,pass];
    
    
    
    NSDictionary *resultDict = [NetUtility getDataWithURLStr:KURLLogin andPostStr:postStr];
    
    
    //    NSDictionary *resultDict =[NetUtility getDataWithURLStr:[NSString stringWithFormat:@"%@%@",KURLLogin,postStr] andPostStr:nil];
    UEXNSLog(@"KURL===%@%@ resultDict=%@",KURLLogin,postStr, resultDict);
    
    if (resultDict) {
        int stauts = [[resultDict objectForKey:@"s"] intValue];
        
        if (stauts==1) {
            
            
            [[NSUserDefaults standardUserDefaults] setObject:name forKey:KUDAppTDWNO];
            [[NSUserDefaults standardUserDefaults] setObject:pass forKey:KUDAppTDWPass];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [AccountController setAccountState:kAccountStateLogin];
            [AccountController setAccountInfo:[resultDict objectForKey:@"d"]];
//            [self.view makeToast:@"登录成功"];
            
            [self initViewControllers];

            
            
            
        }else{
//            [self.view makeToast:[[resultDict objectForKey:@"datas"] objectForKey:@"error"] ];
            
            LoginViewController *rootC = [[LoginViewController alloc]init];
            UINavigationController *rootCNavController = [[UINavigationController alloc] initWithRootViewController:rootC];
            
            self.window.rootViewController = rootCNavController;
            [self.window makeKeyAndVisible];
        }
    }
}

- (void)initQiDongZhiShi
{
//    YinDaoViewController *rootC = [[YinDaoViewController alloc]init];
//    self.window.rootViewController = rootC;
//
//    [self.window makeKeyAndVisible];
}
-(void)CanselZhiYin
{
    [self enterHomePage];
    
    UEXNSLog(@"212121");
}
-(void)ToOtherController:(int)type
{
    int tabIndex = type;
    
    for (int i=0; i<5; i++) {
        UIButton *btn = (UIButton*)[_KlbottomView viewWithTag:(kAppViewTagBottomBtns+i)];
        if (i == tabIndex) {
            if (!btn.selected) {
                btn.selected = YES;
            }
        } else {
            if (btn.selected) {
                btn.selected = NO;
            }
        }
    }
    UINavigationController *newNavController = (UINavigationController*)[_controllersArray objectAtIndex:tabIndex];
    self.window.rootViewController = newNavController;
    [self.window addSubview:newNavController.view];
    [self.window bringSubviewToFront:_KlbottomView];
    
    
    _selectedIndex = tabIndex;
    
}
- (void)initViewControllers
{
    SYViewController *HomeController = [[SYViewController alloc] init];
    UINavigationController *HomeNavController = [[UINavigationController alloc] initWithRootViewController:HomeController];

//    LessonsViewController *LessonController = [[LessonsViewController alloc] init];
//    UINavigationController *LessonNavController = [[UINavigationController alloc] initWithRootViewController:LessonController];
//
//    ZJViewController *ZJController = [[ZJViewController alloc] init];
//    UINavigationController *ZJNavController = [[UINavigationController alloc] initWithRootViewController:ZJController];
//
//    New_MYViewController *MYController = [[New_MYViewController alloc] init];
//    UINavigationController *MYNavController = [[UINavigationController alloc] initWithRootViewController:MYController];
//
    _controllersArray = [NSArray arrayWithObjects:HomeNavController,nil];
//
//    _selectedIndex = 0;

    self.window.rootViewController =[_controllersArray objectAtIndex:0];


    [self.window makeKeyAndVisible];

}
- (void)HFbtnimage {
    
    UIButton *button = (UIButton *)[_KlbottomView viewWithTag:kAppViewTagBottomBtns + 3];
    
    if (button.selected) {
        [button setImage:[AppUtility getLocalImage:@"tabbar_me_select"]  forState:UIControlStateSelected];
        
    }else {
        [button setImage:[AppUtility getLocalImage:@"User"] forState:UIControlStateNormal];
        
    }
    
}
- (void)changeBtnimage {
    
    UIButton *button = (UIButton *)[_KlbottomView viewWithTag:kAppViewTagBottomBtns + 3];
    
    if (button.selected) {
        [button setImage:[AppUtility getLocalImage:@"我的选中红点"] forState:UIControlStateSelected];

    }else {
        [button setImage:[AppUtility getLocalImage:@"我的红点"] forState:UIControlStateNormal];

    }

}
- (void)initBottomView
{
    
    NSArray *titleArray = @[@"首页",@"课程",@"专家",@"我的"];
    _KlbottomView = [[UIView alloc] initWithFrame:CGRectMake(0, [AppUtility screenHeight]-41*theApp.autoSizeScaleY, [AppUtility screenWidth], 41*theApp.autoSizeScaleY)];
    _KlbottomView.backgroundColor = [UIColor whiteColor];
    
//    if (![AccountController isLogin]) {19
//
//        _KlbottomView.hidden = YES;
//    }else{
//        _KlbottomView.hidden = NO;
//    }
    //
    {
        UIImageView *ivBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [AppUtility screenWidth], 1*theApp.autoSizeScaleY)];
        //        ivBG.image = [AppUtility getLocalImage:@"BG@2x"];

        ivBG.backgroundColor = RGBCOLOR(242, 242, 242);
        [_KlbottomView addSubview:ivBG];
        
    }
    //20 34  17 35
    
    for (int i=0; i<4; i++) {
        UIButton *btnTab = [UIButton buttonWithType:UIButtonTypeCustom];
        btnTab.tag = kAppViewTagBottomBtns + i;
        btnTab.frame = CGRectMake1(i*(320/4), 0, 320/4, 41);
        [btnTab setTitle:titleArray[i] forState:UIControlStateNormal];
        
        
         btnTab.titleLabel.font = [UIFont systemFontOfSize:13];
       
//        [btnTab setBackgroundColor:[UIColor redColor]];
        [btnTab setTitleColor:RGBCOLOR(68, 68, 68) forState:UIControlStateNormal];
        [btnTab setTitleColor:RGBCOLOR(69, 166, 254) forState:UIControlStateSelected];;
       
//25 33 19 33 21 33 21 33
        switch (i) {
            case 0:
            {
                btnTab.selected = YES;
                [btnTab setImage:[AppUtility getLocalImage:@"SY"] forState:UIControlStateNormal];
                [btnTab setImage:[AppUtility getLocalImage:@"tabbar_home_select"] forState:UIControlStateSelected];
                
                btnTab.imageEdgeInsets = UIEdgeInsetsMake(0, 29, 19, 29);
                btnTab.titleEdgeInsets = UIEdgeInsetsMake(30, -35, 0, 0);
//                btnTab.imageEdgeInsets = UIEdgeInsetsMake((btnTab.frame.size.height-33)/2, (btnTab.frame.size.width-25)/2, (btnTab.frame.size.height-33)/2, (btnTab.frame.size.width-25)/2);

                break;
            }
            case 1:
            {
                [btnTab setImage:[AppUtility getLocalImage:@"Shape173"] forState:UIControlStateNormal];
                [btnTab setImage:[AppUtility getLocalImage:@"tabbar_course_select"] forState:UIControlStateSelected];

                btnTab.imageEdgeInsets = UIEdgeInsetsMake(0, 29.5, 18, 25.5);
                btnTab.titleEdgeInsets = UIEdgeInsetsMake(30, -34, 0, 0);

                break;
            }

            case 2:
            {
                [btnTab setImage:[AppUtility getLocalImage:@"bottom_zj"] forState:UIControlStateNormal];
                [btnTab setImage:[AppUtility getLocalImage:@"tabbar_expert_select"] forState:UIControlStateSelected];
                btnTab.imageEdgeInsets = UIEdgeInsetsMake(0, 29, 19, 29);
                btnTab.titleEdgeInsets = UIEdgeInsetsMake(30, -35, 0, 0);
//                btnTab.imageEdgeInsets = UIEdgeInsetsMake(8, 30.5, 8, 30.5);


                break;
            }
            case 3:
            {
                [btnTab setImage:[AppUtility getLocalImage:@"User"] forState:UIControlStateNormal];
                [btnTab setImage:[AppUtility getLocalImage:@"tabbar_me_select"] forState:UIControlStateSelected];

//                btnTab.imageEdgeInsets = UIEdgeInsetsMake(8, 30.5, 8, 30.5);
                btnTab.imageEdgeInsets = UIEdgeInsetsMake(0, 29, 19, 29);
                btnTab.titleEdgeInsets = UIEdgeInsetsMake(30, -35, 0, 0);

                break;
            }
           

            default:
                break;
        }

        [btnTab addTarget:self action:@selector(bottomTabClicked:) forControlEvents:UIControlEventTouchUpInside];

        [_KlbottomView addSubview:btnTab];
    }
    
    
    [self.window addSubview:_KlbottomView];
    
}
- (void)changeBtnImage {
   
}
#pragma mark for update
#pragma mark -
- (void)bottomTabClicked:(UIButton*)btn_ {
    

    int tabIndex = (int)btn_.tag - (int)kAppViewTagBottomBtns;
    
    for (int i=0; i<4; i++) {
        UIButton *btn = (UIButton*)[_KlbottomView viewWithTag:(kAppViewTagBottomBtns+i)];
        if (i == tabIndex) {
            if (!btn.selected) {
                btn.selected = YES;

            }
        } else {
            if (btn.selected) {
                btn.selected = NO;

            }
        }
    }
    UINavigationController *newNavController = (UINavigationController*)[_controllersArray objectAtIndex:tabIndex];
    if (tabIndex == _selectedIndex) {
        [newNavController popToRootViewControllerAnimated:YES];
    }else {
        UINavigationController *oldNavController = (UINavigationController*)[_controllersArray objectAtIndex:_selectedIndex];
        [oldNavController popToRootViewControllerAnimated:YES];
        //        [oldNavController.view removeFromSuperview];
        //        [self.window addSubview:newNavController.view];
        self.window.rootViewController = newNavController;
        [self.window addSubview:newNavController.view];
        [self.window bringSubviewToFront:_KlbottomView];
        //        [self.window bringSubviewToFront:menu];
        
        _selectedIndex = tabIndex;
    }
    
}


//#pragma mark ViewController的代理方法
//- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
//    // 你必须重新建立一个后台 seesion 的参照
//    // 否则 NSURLSessionDownloadDelegate 和 NSURLSessionDelegate 方法会因为
//    // 没有 对 session 的 delegate 设定而不会被调用。参见上面的 backgroundURLSession
//    NSURLSession *backgroundSession = [self backgroundURLSession];
//
//    NSLog(@"Rejoining session with identifier %@ %@", identifier, backgroundSession);
//
//    // 保存 completion handler 以在处理 session 事件后更新 UI
//    [self addCompletionHandler:completionHandler forSession:identifier];
//}
//
//#pragma mark Save completionHandler
//- (void)addCompletionHandler:(CompletionHandlerType)handler forSession:(NSString *)identifier {
//    if ([self.completionHandlerDictionary objectForKey:identifier]) {
//        NSLog(@"Error: Got multiple handlers for a single session identifier.  This should not happen.\n");
//    }
//
//    [self.completionHandlerDictionary setObject:handler forKey:identifier];
//}
//
//- (void)callCompletionHandlerForSession:(NSString *)identifier {
//    CompletionHandlerType handler = [self.completionHandlerDictionary objectForKey:identifier];
//
//    if (handler) {
//        [self.completionHandlerDictionary removeObjectForKey: identifier];
//        NSLog(@"Calling completion handler for session %@", identifier);
//
//        handler();
//    }
//}
//
//#pragma mark - Local Notification
//- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
//    [[UIApplication sharedApplication] cancelAllLocalNotifications];
//
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"下载通知"
//                                                    message:notification.alertBody
//                                                   delegate:nil
//                                          cancelButtonTitle:@"确定"
//                                          otherButtonTitles:nil];
//    [alert show];
//
//    // 图标上的数字减1
//    application.applicationIconBadgeNumber -= 1;
//}
//
//
//
//- (void)initLocalNotification {
//    self.localNotification = [[UILocalNotification alloc] init];
//    self.localNotification.fireDate = [[NSDate date] dateByAddingTimeInterval:5];
//    self.localNotification.alertAction = nil;
//    self.localNotification.soundName = UILocalNotificationDefaultSoundName;
//    self.localNotification.alertBody = @"下载完成了！";
//    self.localNotification.applicationIconBadgeNumber = 1;
//    self.localNotification.repeatInterval = 0;
//}
//
//- (void)sendLocalNotification {
//    [[UIApplication sharedApplication] scheduleLocalNotification:self.localNotification];
//}


//#pragma mark - backgroundURLSession
//- (NSURLSession *)backgroundURLSession {
//    static NSURLSession *session = nil;
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        NSString *identifier = @"com.yourcompany.appId.BackgroundSession";
//        NSURLSessionConfiguration* sessionConfig = nil;
//#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000)
//        sessionConfig = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:identifier];
//#else
//        sessionConfig = [NSURLSessionConfiguration backgroundSessionConfiguration:identifier];
//#endif
//        session = [NSURLSession sessionWithConfiguration:sessionConfig
//                                                delegate:self
//                                           delegateQueue:[NSOperationQueue mainQueue]];
//    });
//
//    return session;
//}
//
//#pragma mark - Public Mehtod
//- (void)beginDownloadWithUrl:(NSString *)downloadURLString {
//    NSURL *downloadURL = [NSURL URLWithString:downloadURLString];
//    NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL];
//    //cancel last download task
//    [self.downloadTask cancelByProducingResumeData:^(NSData * resumeData) {
//
//    }];
//
//    self.downloadTask = [self.backgroundSession downloadTaskWithRequest:request];
//    [self.downloadTask resume];
//}
//
//- (void)pauseDownload {
//    __weak __typeof(self) wSelf = self;
//    [self.downloadTask cancelByProducingResumeData:^(NSData * resumeData) {
//        __strong __typeof(wSelf) sSelf = wSelf;
//        sSelf.resumeData = resumeData;
//    }];
//}
//
//- (void)continueDownload {
//    if (self.resumeData) {
//        if (IS_IOS10ORLATER) {
//            self.downloadTask = [self.backgroundSession downloadTaskWithCorrectResumeData:self.resumeData];
//        } else {
//            self.downloadTask = [self.backgroundSession downloadTaskWithResumeData:self.resumeData];
//        }
//        [self.downloadTask resume];
//        self.resumeData = nil;
//    }
//}
//- (void)CancelDownload {
//    [self.downloadTask cancel];
//}
//- (BOOL)isValideResumeData:(NSData *)resumeData
//{
//    if (!resumeData || resumeData.length == 0) {
//        return NO;
//    }
//    return YES;
//}
//
//#pragma mark - NSURLSessionDownloadDelegate
//- (void)URLSession:(NSURLSession *)session
//      downloadTask:(NSURLSessionDownloadTask *)downloadTask
//didFinishDownloadingToURL:(NSURL *)location {
//
//    NSLog(@"downloadTask:%lu didFinishDownloadingToURL:%@", (unsigned long)downloadTask.taskIdentifier, location);
//    NSString *locationString = [location path];
//    NSString *finalLocation = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%lufile",(unsigned long)downloadTask.taskIdentifier]];
//    NSError *error;
//    [[NSFileManager defaultManager] moveItemAtPath:locationString toPath:finalLocation error:&error];
//
//    // 用 NSFileManager 将文件复制到应用的存储中
//    // ...
//
//    // 通知 UI 刷新
//}
//- (void)URLSession:(NSURLSession *)session
//      downloadTask:(NSURLSessionDownloadTask *)downloadTask
// didResumeAtOffset:(int64_t)fileOffset
//expectedTotalBytes:(int64_t)expectedTotalBytes {
//
//    NSLog(@"fileOffset:%lld expectedTotalBytes:%lld",fileOffset,expectedTotalBytes);
//
//
//}
//
//- (void)URLSession:(NSURLSession *)session
//      downloadTask:(NSURLSessionDownloadTask *)downloadTask
//      didWriteData:(int64_t)bytesWritten
// totalBytesWritten:(int64_t)totalBytesWritten
//totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
//
//    NSLog(@"downloadTask:%lu percent:%.2f%%",(unsigned long)downloadTask.taskIdentifier,(CGFloat)totalBytesWritten / totalBytesExpectedToWrite * 100);
//    NSString *strProgress = [NSString stringWithFormat:@"%.2f",(CGFloat)totalBytesWritten / totalBytesExpectedToWrite];
//    [self postDownlaodProgressNotification:strProgress];
//
//    /** 这次获取字节数的时间. */
////    NSDate *currentDate = [NSDate date];
////
////    /** 两次获取字节数的时间间隔. */
////    NSTimeInterval time =[currentDate timeIntervalSinceDate:_lastDate];
////
////    /** 时间间隔大于1秒, 再更新UI. */
//////    if (time >= 1) {
////        /** 算出下载速度. */
////        NSString *speedString = [NSString stringWithFormat:@"%.2lfKB", bytesWritten / time / 2048];
////        /** 更新UI.(注意的部分请看 progressLabel.text的注.) */
////        //        _speedLabel.text = speedString;
////
////        /** 将这次的时间赋值给lastData属性. */
////        _lastDate = currentDate;
////
////        [self postDownlaodSpeedNotification:speedString];
////    }
//}
//
//- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
//    NSLog(@"Background URL session %@ finished events.\n", session);
//
//    if (session.configuration.identifier) {
//        // 调用在 -application:handleEventsForBackgroundURLSession: 中保存的 handler
//        [self callCompletionHandlerForSession:session.configuration.identifier];
//    }
//}
//
///*
// * 该方法下载成功和失败都会回调，只是失败的是error是有值的，
// * 在下载失败时，error的userinfo属性可以通过NSURLSessionDownloadTaskResumeData
// * 这个key来取到resumeData(和上面的resumeData是一样的)，再通过resumeData恢复下载
// */
//- (void)URLSession:(NSURLSession *)session
//              task:(NSURLSessionTask *)task
//didCompleteWithError:(NSError *)error {
//
//    if (error) {
//        // check if resume data are available
//        if ([error.userInfo objectForKey:NSURLSessionDownloadTaskResumeData]) {
//            NSData *resumeData = [error.userInfo objectForKey:NSURLSessionDownloadTaskResumeData];
//            //通过之前保存的resumeData，获取断点的NSURLSessionTask，调用resume恢复下载
//            self.resumeData = resumeData;
//        }
//    } else {
//        [self sendLocalNotification];
//        [self postDownlaodProgressNotification:@"1"];
//    }
//}
//
//- (void)postDownlaodProgressNotification:(NSString *)strProgress {
//    NSDictionary *userInfo = @{@"progress":strProgress};
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [[NSNotificationCenter defaultCenter] postNotificationName:kDownloadProgressNotification object:nil userInfo:userInfo];
//    });
//}
//- (void)postDownlaodSpeedNotification:(NSString *)speed {
//    NSDictionary *userInfo = @{@"speed":speed};
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [[NSNotificationCenter defaultCenter] postNotificationName:kDownloadSpeedNotification object:nil userInfo:userInfo];
//    });
//}
#pragma mark -

- (void)onGetNetworkState:(int)iError
{
    if (0 == iError) {
        UEXNSLog(@"联网成功");
    }
    else{
        UEXNSLog(@"onGetNetworkState %d",iError); }
}
- (void)onGetPermissionState:(int)iError
{
    if (0 == iError) {
        UEXNSLog(@"授权成功"); }
    else {
        UEXNSLog(@"onGetPermissionState %d",iError);
        
    }
}
//- (void)applicationWillResignActive:(UIApplication *)application {
//    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
//    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
//
//    // 图标上的数字减1
//    application.applicationIconBadgeNumber -= 1;
//}
//
//
//- (void)applicationDidEnterBackground:(UIApplication *)application {
//    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
//    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
//}
//
//
//- (void)applicationWillEnterForeground:(UIApplication *)application {
//    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
//}
//
//
//- (void)applicationDidBecomeActive:(UIApplication *)application {
//    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
//}
//
//
//- (void)applicationWillTerminate:(UIApplication *)application {
//    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
//}
//- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
//
//    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
//    [JPUSHService registerDeviceToken:deviceToken];
//}
//- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
//    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
//}
//#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
//- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
//}
//// Called when your app has been activated by the user selecting an action from
//// a local notification.
//// A nil action identifier indicates the default action.
//// You should call the completion handler as soon as you've finished handling
//// the action.
//- (void)application:(UIApplication *)application
//handleActionWithIdentifier:(NSString *)identifier
//forLocalNotification:(UILocalNotification *)notification
//  completionHandler:(void (^)())completionHandler {
//}
//
//// Called when your app has been activated by the user selecting an action from
//// a remote notification.
//// A nil action identifier indicates the default action.
//// You should call the completion handler as soon as you've finished handling
//// the action.
//- (void)application:(UIApplication *)application
//handleActionWithIdentifier:(NSString *)identifier
//forRemoteNotification:(NSDictionary *)userInfo
//  completionHandler:(void (^)())completionHandler {
//}
//#endif
//
//- (void)application:(UIApplication *)application
//didReceiveRemoteNotification:(NSDictionary *)userInfo {
//    [JPUSHService handleRemoteNotification:userInfo];
//    NSLog(@"iOS6及以下系统，收到通知:");
//}
//
//- (void)application:(UIApplication *)application
//didReceiveRemoteNotification:(NSDictionary *)userInfo
//fetchCompletionHandler:
//(void (^)(UIBackgroundFetchResult))completionHandler {
//    [JPUSHService handleRemoteNotification:userInfo];
//    NSLog(@"iOS7及以上系统，收到通知:");
//
//    if ([[UIDevice currentDevice].systemVersion floatValue]<10.0 || application.applicationState>0) {
//    }
//
//    completionHandler(UIBackgroundFetchResultNewData);
//}
//
//- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
//    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
//    NSLog(@"收到本地通知");
//}
//
////#ifdef NSFoundationVersionNumber_iOS_9_x_Max
//#pragma mark- JPUSHRegisterDelegate
//- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
//    NSDictionary * userInfo = notification.request.content.userInfo;
//
//    UNNotificationRequest *request = notification.request; // 收到推送的请求
//    UNNotificationContent *content = request.content; // 收到推送的消息内容
//
//    NSNumber *badge = content.badge;  // 推送消息的角标
//    NSString *body = content.body;    // 推送消息体
//    UNNotificationSound *sound = content.sound;  // 推送消息的声音
//    NSString *subtitle = content.subtitle;  // 推送消息的副标题
//    NSString *title = content.title;  // 推送消息的标题
//
//    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//        [JPUSHService handleRemoteNotification:userInfo];
//        NSLog(@"iOS10 前台收到远程通知:");
//
//
//
//
//    }
//    else {
//        // 判断为本地通知
//        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
//
//
//
//        //        SJ_SYViewController *rootC = [[SJ_SYViewController alloc]init];
//        //        UINavigationController *rootCNavController = [[UINavigationController alloc] initWithRootViewController:rootC];
//        //
//        //        self.window.rootViewController = rootCNavController;
//        //        [self.window makeKeyAndVisible];
//    }
//    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
//}
//
//- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
//
//    NSDictionary * userInfo = response.notification.request.content.userInfo;
//    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
//    UNNotificationContent *content = request.content; // 收到推送的消息内容
//
//    NSNumber *badge = content.badge;  // 推送消息的角标
//    NSString *body = content.body;    // 推送消息体
//    UNNotificationSound *sound = content.sound;  // 推送消息的声音
//    NSString *subtitle = content.subtitle;  // 推送消息的副标题
//    NSString *title = content.title;  // 推送消息的标题
//
//    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//        [JPUSHService handleRemoteNotification:userInfo];
//        NSLog(@"iOS10 收到远程通知:");
//
//        UINavigationController *rrrVC = (UINavigationController *)self.window.rootViewController;
//        MesgViewController *messageVC = [[MesgViewController alloc]init];
//
//        [rrrVC  pushViewController:messageVC animated:YES];
//
//    }
//    else {
//        // 判断为本地通知
//        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
//
//
//    }
//
//    completionHandler();  // 系统要求执行这个方法
//}
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
//
//
//    //    AlixPayResult* result = [self handleOpenURL:url];
//    //
//    //    if (result) {
//    //
//    //        NSString * query = [[url query] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    //
//    //        [_makeSureViewC paymentResult:query];
//    //
//    //    }
//
//    if ([url.host isEqualToString:@"safepay"]) {
//
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//
//            //                                             [_makeSureViewC paymentResult:resultDic];
//
//        }];
//
//    }
//    return [WXApi handleOpenURL:url delegate:self];
//
//
//
//
//    return YES;
//}
//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
//{
//    [WXApi handleOpenURL:url delegate:self];
//
//    if ([url.host isEqualToString:@"safepay"]) {
//        //跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//        }];
//    }
//    return YES;
//}
//
////独立客户端回调函数
//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
//
//    [WXApi handleOpenURL:url delegate:self];
//     [TencentOAuth HandleOpenURL:url];
//    return YES;
//}

//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//
//    // 微信的支付回调
//    if ([url.host isEqualToString:@"pay"]) {
//        return [WXApi handleOpenURL:url delegate:self];
//    }
//
//    if ([url.host isEqualToString:@"safepay"]) {
//        //跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//        }];
//    }
//    return YES;
//}
//
//// NOTE: 9.0以后使用新API接口
//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
//{
//
//    // 微信的支付回调
//    if ([url.host isEqualToString:@"pay"]) {
//
//
//        return [WXApi handleOpenURL:url delegate:self];
//    }
//    if ([url.host isEqualToString:@"safepay"]) {
//        //跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//
//            if ([resultDic[@"resultStatus"] intValue] == 9000) {
//                NSNotification *notification = [NSNotification notificationWithName:ORDER_AliPAY_NOTIFICATION object:@"successful"];
//                [[NSNotificationCenter defaultCenter] postNotification:notification];
//            }
//        }];
//
//
//    }
//    return YES;
//}


//////
//- (void)parse:(NSURL *)url application:(UIApplication *)application {
//
//    //结果处理
//    AlixPayResult* result = [self handleOpenURL:url];
//
//    if (result) {
//
//        NSString * query = [[url query] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//
//        [_makeSureViewC paymentResult:query];
//
//    }
//}
////
////
//- (AlixPayResult *)resultFromURL:(NSURL *)url {
//    NSString * query = [[url query] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//#if ! __has_feature(objc_arc)
//    return [[[AlixPayResult alloc] initWithString:query] autorelease];
//#else
//    return [[AlixPayResult alloc] initWithString:query];
//#endif
//}
//////
//- (AlixPayResult *)handleOpenURL:(NSURL *)url {
//    AlixPayResult * result = nil;
//
//    if (url != nil && [[url host] compare:@"safepay"] == 0) {
//        result = [self resultFromURL:url];
//    }
//
//    return result;
//}


//- (void)sendPay
//{
//    //从服务器获取支付参数，服务端自定义处理逻辑和格式
//    //订单标题
//    NSString *ORDER_NAME    = @"Ios服务器端签名支付 测试";
//    //订单金额，单位（元）
//    NSString *ORDER_PRICE   = @"0.01";
//
//    //根据服务器端编码确定是否转码
//    NSStringEncoding enc;
//    //if UTF8编码
//    //enc = NSUTF8StringEncoding;
//    //if GBK编码
//    enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
//    NSString *urlString = [NSString stringWithFormat:@"%@?plat=ios&order_no=%@&product_name=%@&order_price=%@",
//                           @"http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php",
//                           [[NSString stringWithFormat:@"%ld",time(0)] stringByAddingPercentEscapesUsingEncoding:enc],
//                           [ORDER_NAME stringByAddingPercentEscapesUsingEncoding:enc],
//                           ORDER_PRICE];
//
//    //解析服务端返回json数据
//    NSError *error;
//    //加载一个NSURL对象
//    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
//    //将请求的url数据放到NSData对象中
//    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//    if ( response != nil) {
//        NSMutableDictionary *dict = NULL;
//        //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
//        dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
//
//        NSLog(@"url:%@",urlString);
//        if(dict != nil){
//            NSMutableString *retcode = [dict objectForKey:@"retcode"];
//            if (retcode.intValue == 0){
//                NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
//
//                //调起微信支付
//                PayReq* req             = [[PayReq alloc] init];
//                req.openID              = [dict objectForKey:@"appid"];
//                req.partnerId           = [dict objectForKey:@"partnerid"];
//                req.prepayId            = [dict objectForKey:@"prepayid"];
//                req.nonceStr            = [dict objectForKey:@"noncestr"];
//                req.timeStamp           = stamp.intValue;
//                req.package             = [dict objectForKey:@"package"];
//                req.sign                = [dict objectForKey:@"sign"];
//                [WXApi sendReq:req];
//                //日志输出
//                NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",req.openID,req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
//            }else{
//                [self.window makeToast:[dict objectForKey:@"retmsg"]];
//            }
//        }else{
//            [self.window makeToast:@"服务器返回错误，未获取到json对象"];
//        }
//    }else{
//        [self.window makeToast:@"服务器返回错误"];
//    }
//}

//-(void) onResp:(BaseResp*)resp
//{
//    if([resp isKindOfClass:[PayResp class]]){
//
//        switch (resp.errCode) {
//            case WXSuccess:{
//
//                UEXNSLog(@"－－－－－支付成功");
//
//                [self.window makeToast:@"支付成功"];
//
//
//                NSNotification *notification = [NSNotification notificationWithName:ORDER_PAY_NOTIFICATION object:@"success"];
//                [[NSNotificationCenter defaultCenter] postNotification:notification];
//            }
//                break;
//            default:{
//                UEXNSLog(@"－－－－－支付失败");
//
//            }
//                break;
//
//        }
//    }
//}



@end
